package com.atguigu.tingshu.payment.service.impl;

import cn.hutool.core.lang.Assert;
import com.atguigu.tingshu.account.AccountFeignClient;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.account.RechargeInfo;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.model.payment.PaymentInfo;
import com.atguigu.tingshu.order.client.OrderFeignClient;
import com.atguigu.tingshu.payment.mapper.PaymentInfoMapper;
import com.atguigu.tingshu.payment.service.PaymentInfoService;
import com.atguigu.tingshu.user.client.UserFeignClient;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wechat.pay.java.service.payments.model.Transaction;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@SuppressWarnings({"all"})
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentInfoService {

    @Autowired
    private OrderFeignClient orderFeignClient;
    @Autowired
    private AccountFeignClient accountFeignClient;
    @Autowired
    private PaymentInfoMapper paymentInfoMapper;

    @Override
    public PaymentInfo savePaymentInfo(String paymentType, String orderNo) {
        //获取订单信息
        PaymentInfo paymentInfo = this.getOne(new LambdaQueryWrapper<PaymentInfo>()
                .eq(PaymentInfo::getOrderNo, orderNo));
        //如果存在返回查询结果
        if (paymentInfo != null){
            return paymentInfo;
        }

        //如果不存在,封装新订单信息
        paymentInfo = new PaymentInfo();
        paymentInfo.setUserId(AuthContextHolder.getUserId());
        paymentInfo.setPaymentType(paymentType);
        paymentInfo.setOrderNo(orderNo);
        paymentInfo.setPaymentStatus(SystemConstant.PAYMENT_STATUS_UNPAID);
        paymentInfo.setPayWay(SystemConstant.ORDER_PAY_WAY_WEIXIN);
        //消费类型为订单支付,调用订单服务远程接口查询订单信息
        if (paymentInfo.getPaymentType().equals(SystemConstant.PAYMENT_TYPE_ORDER)) {
            OrderInfo orderInfo = orderFeignClient.getOrderInfo(orderNo).getData();
            Assert.notNull(orderInfo, "未查询到订单信息");
            if (orderInfo.getOrderStatus().equals(SystemConstant.ORDER_STATUS_CANCEL)) {
                throw new RuntimeException("该订单已取消");
            } else if (orderInfo.getOrderStatus().equals(SystemConstant.ORDER_STATUS_PAID)) {
                throw new RuntimeException("该订单已支付");
            } else if (orderInfo.getOrderStatus().equals(SystemConstant.ORDER_STATUS_UNPAID)) {
                paymentInfo.setAmount(orderInfo.getOrderAmount());
                paymentInfo.setContent(orderInfo.getOrderTitle());
            }
        }
        //消费类型为余额充值,调用账户服务远程接口查询订单信息
        if (paymentInfo.getPaymentType().equals(SystemConstant.PAYMENT_TYPE_RECHARGE)) {
            RechargeInfo rechargeInfo = accountFeignClient.getRechargeInfo(orderNo).getData();
            Assert.notNull(rechargeInfo, "未查询到订单信息");
            if (rechargeInfo.getRechargeStatus().equals(SystemConstant.PAYMENT_STATUS_PAID)) {
                throw new RuntimeException("该订单已支付");
            }
            paymentInfo.setAmount(rechargeInfo.getRechargeAmount());
            paymentInfo.setContent("充值金额: " + rechargeInfo.getRechargeAmount());
        }
//        从第三方wx支付接口获取
//        paymentInfo.setOutTradeNo();
//        paymentInfo.setCallbackTime();
//        paymentInfo.setCallbackContent();

        this.save(paymentInfo);

        return paymentInfo;
    }

    @GlobalTransactional(rollbackFor = Exception.class)
    @Override
    public void updatePaymentInfo(Transaction transaction) {
        //根据交易信息查询本地交易记录
        PaymentInfo paymentInfo = paymentInfoMapper.selectOne(
                new LambdaQueryWrapper<PaymentInfo>()
                        .eq(PaymentInfo::getOutTradeNo, transaction.getOutTradeNo()));
        String paymentStatus = paymentInfo.getPaymentStatus();
        if (SystemConstant.PAYMENT_STATUS_PAID.equals(paymentStatus)){
            throw new RuntimeException("订单已支付");
        }

        //若订单尚未支付,更新订单支付状态
        paymentInfo.setOutTradeNo(transaction.getOutTradeNo());
        paymentInfo.setPaymentStatus(SystemConstant.PAYMENT_STATUS_PAID);
        paymentInfo.setCallbackTime(new Date());
        paymentInfo.setCallbackContent(transaction.toString());
        paymentInfoMapper.updateById(paymentInfo);

        //根据交易类型,通知不同服务交易成功
        String paymentType = paymentInfo.getPaymentType();
        if (SystemConstant.PAYMENT_TYPE_ORDER.equals(paymentType)){
            //为订单交易,调用订单服务,更新订单状态
            Result result = orderFeignClient.orderPaySuccess(transaction.getOutTradeNo());
            if (result.getCode() != 200){
                throw new GuiguException(result.getCode(), result.getMessage());
            }
        }
        if (SystemConstant.PAYMENT_TYPE_RECHARGE.equals(paymentType)){
            //为订单交易,调用订单服务,更新订单状态
            Result result = accountFeignClient.rechargePaySuccess(transaction.getOutTradeNo());
            if (result.getCode() != 200){
                throw new GuiguException(result.getCode(), result.getMessage());
            }
        }
    }
}
